package com.ebupt.migu.music.service.impl;

import com.ebupt.migu.music.entity.DataSyncEntity;
import com.ebupt.migu.music.mapper.DataSyncMapper;
import com.ebupt.migu.music.service.DataSyncService;
import com.ebupt.migu.music.utils.SFTPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @description: TODO
 * @author: liuyangyang@ebupt.com
 * @date: 2021/5/24 16:43
 */
@Slf4j
@Service
public class DataSyncServiceImpl implements DataSyncService {

    @Autowired
    private SFTPUtils sftpUtils;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DataSyncMapper dataSyncMapper;
    @Autowired
    private ThreadPoolTaskExecutor sftpThreadPool;

    /**
     * SFTP数据同步
     */
    @Override
    public void data_sync() throws Exception {
        // 查询新建的SFPT任务
        DataSyncEntity sync = dataSyncMapper.query_sftp_data_sync();
        if (null == sync) {
            return;
        }
        dataSyncMapper.update_sftp_status(sync.getStrategyId(), "2");
        // 查询策略详情
        HashMap<String, Object> strategy = dataSyncMapper.query_strategy_info(sync.getStrategyId());
        // 白名单成员
        List<String> whites = new ArrayList<>();
        // 黑名单成员
        List<String> blacks = new ArrayList<>();
        // 白名单： 1-添加白名单
        String[] white = null;
        // 黑名单： 1-剔除黑名单
        String[] black = null;
        if (null != strategy.get("white")) {
            // 多选白名单
            white = String.valueOf(strategy.get("white")).split(",");
        }
        if (null != strategy.get("black")) {
            // 多选黑名单
            black = String.valueOf(strategy.get("black")).split(",");
        }
        // 添加白名单用户
        if (white != null && white.length > 0) {
            log.info("添加白名单用户");
            whites = roster_members(white, sync.getDataType());
        }
        // 剔除黑名单用户
        if (black != null && black.length > 0) {
            log.info("剔除黑名单用户");
            blacks = roster_members(black, sync.getDataType());
        }
        // 创建本地文件
        String path = sync.getLocalPath() + sync.getFileName();
        File file = new File(path);
        // 文件不存在或者空文件，创建文件并记录人群明细数据
        if (!file.exists() || file.length() == 0) {
            file.createNewFile();
            log.info("创建文件");
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            // 记录白名单
            if (whites != null) {
                for (String w : whites) {
                    log.info("白名单用户：{}", w);
                    bufferedWriter.write(w + "|^|" + sync.getStrategyId());
                    bufferedWriter.newLine();
                }
            }
            // 记录圈选出的人群
            Cursor<String> cursor = null;
            switch (sync.getDataType()) {
                case "1":
                    cursor = redisTemplate.opsForSet().scan(sync.getGroupId() + "-phone", ScanOptions.NONE);
                    break;
                case "2":
                    cursor = redisTemplate.opsForSet().scan(sync.getGroupId() + "-uid", ScanOptions.NONE);
                    break;
//                case "3":
//                    cursor = redisTemplate.opsForSet().scan(sync.getGroupId() + "-imei", ScanOptions.NONE);
//                    break;
            }
            while (cursor.hasNext()) {
                String data = cursor.next();
                if (blacks != null && blacks.contains(data)) {
                    continue;
                }
                if (whites != null && whites.contains(data)) {
                    continue;
                }
                bufferedWriter.write(data + "|^|" + sync.getStrategyId());
                bufferedWriter.newLine();
            }
            bufferedWriter.close();
        }
        if (file.length() > 0){
             sftpThreadPool.submit(() -> {
                try {
                    boolean success = sftpUtils.uploadFile(sync.getFileName(), file);
                    log.info("上传文件：{}", success);
                    if(success){
                        dataSyncMapper.update_sftp_status(sync.getStrategyId(), "3");
                        log.info("同步完成：{}", sync.getFileName());
                    }else {
                        log.info("同步失败：{}", sync.getFileName());
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    /**
     * 查询名单中的用户
     */
    private List<String> roster_members(String[] ids, String dataType) {
        List<String> members = new ArrayList<>();
        for (String id : ids) {
            List<String> rosters = new ArrayList<>();
            switch (dataType) {
                case "1":
                    rosters = dataSyncMapper.query_roster_msisdns(id);
                    break;
                case "2":
                    rosters = dataSyncMapper.query_roster_uids(id);
                    break;
                case "3":
                    List<String> imeis = dataSyncMapper.query_roster_imeis(id);
                    List<String> idfas = dataSyncMapper.query_roster_idfas(id);
                    if (null != imeis && !imeis.isEmpty()) {
                        rosters.addAll(imeis);
                    }
                    if (null != idfas && !idfas.isEmpty()) {
                        rosters.addAll(idfas);
                    }
                    break;
            }
            if (null != rosters && !rosters.isEmpty()) {
                members.addAll(rosters);
            }
        }
        return members;
    }
}
